package com.haven.webrobotserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.haven.webrobotserver.utils.FileUtil;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileUpLoadController {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @PostMapping("logUpload")
    public JSONObject logUpload(HttpServletRequest request) throws IOException {
        JSONObject result = new JSONObject();

        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");

        if (files.isEmpty()) {
            result.put("msg","文件为空");
            result.put("status",200);
            return result;
        }

        String fileName = files.get(0).getOriginalFilename();
        String rootPath = "D:\\webserverLogs\\";
        File dest = new File(rootPath + fileName);
        try {
            files.get(0).transferTo(dest);
            logger.info("上传成功");
            result.put("msg","文件上传成功");

        } catch (IOException e) {
            logger.error(e.toString(), e);
        }

        /*解压*/
        String fileNameWithOutZip = fileName.replace(".zip", "");

        boolean b = FileUtil.unZip(dest, "D:\\webserverLogs\\" + fileNameWithOutZip);

        if(!b){
            logger.info("日志解压失败！");
        }else{
            dest.delete();
        }

        return result;
    }


}
